#include <iostream>
#include <filesystem>
#include <string>
#include <fstream>
#include <sstream>
#include <blend2d-impl.h>
BLImage createBitmapFromData(const char* data, size_t size) {
    BLImage img;
    if (img.readFromData(data, size) != BL_SUCCESS) {
        throw std::runtime_error("createBitmapFromData exception.");
    }
    return img;
}
BLImage LoadFromFile(const char* _path) {
	std::ifstream _ifs(_path, std::ios::binary);
	_ifs.seekg(0, std::ios::end);
	size_t _fsz = (size_t)_ifs.tellg();
	_ifs.seekg(0, std::ios::beg);
	std::vector<char> _bytes;
	_bytes.resize(_fsz);
	_ifs.read(&_bytes[0], (std::streamsize)_fsz);
	_ifs.close();

	return createBitmapFromData(&_bytes[0], _bytes.size());
}
std::unique_ptr<BLContext> initGraphics(int width,int height,std::unique_ptr<BLImage>& image){
    auto graphics = std::make_unique<BLContext>(*image);//, ctxInfo
    graphics->setCompOp(BL_COMP_OP_SRC_OVER);
    graphics->setRenderingQuality(BL_RENDERING_QUALITY_ANTIALIAS);
    return graphics;
}
int main() {
    std::string file = "test.png";
    int width = 750, height = 940;
    auto pixelFormat = BL_FORMAT_PRGB32;
    auto inputBitmap = std::make_unique<BLImage>(width, height, pixelFormat);
    auto outputBitmap = std::make_unique<BLImage>(width, height, pixelFormat);
    auto input = initGraphics(width,height,inputBitmap);
    auto output = initGraphics(width,height,outputBitmap);
    //加载图片
    auto image = LoadFromFile(file.c_str());
    //绘制图片
    input->begin(*inputBitmap);
    input->blitImage(BLPointI(0,0), image);
    input->end();
    inputBitmap->convert(BL_FORMAT_A8);
    //填充黑色背景
    output->setFillStyle(BLRgba32(0xFF000000));//黑色
    output->fillRect(BLRectI(0, 0, width, height));
    output->begin(*outputBitmap);
    output->blitImage(BLPointI(0,0), *inputBitmap);
    output->end();
    //保存图片
    const char* fileName = "out.png";//(dirPath / (std::to_string(frame) + ".png")).string();
    outputBitmap->writeToFile(fileName);

    std::cin.get();
    return 0;
}
